const fs = require("fs")
const esprima = require("esprima")
const estraverse = require("estraverse")
const escodegen = require("escodegen")
const iconv = require("iconv-lite")
const base_ast = require("../../tools/es_ast_tool")
const {convertNodesIntoNode} = require("jsdom/lib/jsdom/living/node");

function evaluateExpression(node) {
    try {
        return eval(node.source());
    } catch (e) {
        return node;
    }
}

function eval_constant1(ast) {
    estraverse.replace(ast, {
        enter: (node, parent) => {
            if (node.type === 'UnaryExpression' && node.argument.type === 'ArrayExpression'&&node.operator==="+") {
                console.log(node);
                var element = node.argument.elements;
                console.log(element, element.length);
                if(element.length===0){
                    var val = 0;
                    return {
                        type:esprima.Syntax.Literal,
                        value:val,
                        raw:val,
                    }
                }
            }

        }
    });
}

function eval_constant2(ast){
    estraverse.replace(ast, {
        enter:(node, parent)=>{
            if(node.type==="UnaryExpression" &&node.argument.type==="Literal"&&(node.operator==="!"||node.operator==="+")){
                if(node.operator==="!"){
                    var val = node.argument.value;
                    return {
                        type:esprima.Syntax.Literal,
                        value:!val,
                        raw:!val,
                    }
                }
                if(node.operator==="+"){
                    var val = node.argument.value;
                    return {
                        type:esprima.Syntax.Literal,
                        value:+val,
                        raw:+val,
                    }
                }

            }
        }
    });
}

function eval_constant3(ast){
    estraverse.replace(ast, {
        enter:(node, parent)=>{
            if(node.type==="UnaryExpression" &&node.argument.type==="Literal"&&node.operator==="+"){
                var val = node.argument.value;
                console.log("val:"+val);
                console.log(node);
                return {
                    type:esprima.Syntax.Literal,
                    value:+val,
                    raw:+val,
                }
            }

        }
    });
}



var content = fs.readFileSync("./PD18EXRU.js",{encoding:"binary"});
// var content = fs.readFileSync("./1.js",{encoding:"binary"});
var buf = new Buffer.from(content, "binary");
var code = iconv.decode(buf, "utf-8");
var ast = esprima.parse(code);
eval_constant1(ast);
eval_constant2(ast);
eval_constant3(ast);
for (let i = 0; i < 10; i++) {
    base_ast.binary_tool(ast);
}

var new_code = escodegen.generate(ast);
//
fs.writeFile('./1.js', new_code, (err) => {
});
